<?
/*
	Author:Apple
	Version:1.1
	Edit Last:2010-04-16 16:39:48
	File Name:global.func.php
*/

if(!defined('IN_SITE'))
{
	exit('Access Denied');
}

/*
 * 统计店铺数量
 */
function statshops() {
	global $db, $tablepre;
	$i = 0;
	$CreateFile = 'data/cache/cache_statshops.php';
	$FileString = "";
	$FileString .= "<?php \n \$statshops = array( \n";
	$sgrade3 = $db->result_first("SELECT count(*) FROM {$tablepre}shops WHERE sgrade='3' AND isaudit='1'");
	$sgrade2 = $db->result_first("SELECT count(*) FROM {$tablepre}shops WHERE sgrade='2' AND isaudit='1'");
	$sgrade1 = $db->result_first("SELECT count(*) FROM {$tablepre}shops WHERE sgrade='1' AND isaudit='1'");
	$FileString .= "\t'all' => '".($sgrade3+$sgrade2+$sgrade1)."',\n";
	$FileString .= "\t'sgrade3' => '".$sgrade3."',\n";
	$FileString .= "\t'sgrade2' => '".$sgrade2."',\n";
	$FileString .= "\t'sgrade1' => '".$sgrade1."',";
	$FileString .= "\n );\n?>";
	if ( $fh = fopen( $CreateFile, 'w' ) )
	{
	   fputs ($fh, $FileString, strlen($FileString) );
	   fclose($fh);
	   @chmod ($Creatfile,0777);
	}
}

function r_newshop() {
	global $siteurl, $db, $tablepre;
	$newshop = $db->fetch_all("SELECT sid, shopname FROM {$tablepre}shops WHERE isaudit='1' ORDER BY sid DESC LIMIT 0, 10");
	ob_start();
	include template("r_newshop");
	$file = SITE_ROOT.'ssi/r_newshop.htm';
	createhtml($file);
}

function r_hotshop() {
	global $siteurl, $db, $tablepre;
	$hotshop = $db->fetch_all("SELECT sid, shopname FROM {$tablepre}shops WHERE isaudit='1' ORDER BY views DESC LIMIT 0, 10");
	ob_start();
	include template("r_hotshop");
	$file = SITE_ROOT.'ssi/r_hotshop.htm';
	createhtml($file);
}

function r_zt() {
	global $siteurl, $db, $tablepre;
	$r_zt = $db->fetch_all("SELECT title, showimg, islink, url FROM {$tablepre}content WHERE special = '1' AND status > 0 ORDER BY pubtime DESC LIMIT 0, 10");
	ob_start();
	include template("r_zt");
	$file = SITE_ROOT.'ssi/r_zt.htm';
	createhtml($file);
}

function shophy(){
	global $siteurl, $db, $tablepre;
	//读取分类缓存
	if(is_file(CACHE_PATH.'cache_category.php'))
	{
		@include CACHE_PATH.'cache_category.php';
	}
	else
	{
		updatecache('category');
		@include CACHE_PATH.'cache_category.php';
	}
	$category = $_SCACHE['category'];
	$area = $db->fetch_all("SELECT aid, aname FROM {$tablepre}area");
	$zone = $db->fetch_all("SELECT zid, zname FROM {$tablepre}zone WHERE fid=0");
	ob_start();
	include template("shophy");
	$file = SITE_ROOT.'ssi/shophy.htm';
	createhtml($file);
}

function ip()
{
	if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown'))
	{
		$ip = getenv('HTTP_CLIENT_IP');
	}
	elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown'))
	{
		$ip = getenv('HTTP_X_FORWARDED_FOR');
	}
	elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown'))
	{
		$ip = getenv('REMOTE_ADDR');
	}
	elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown'))
	{
		$ip = $_SERVER['REMOTE_ADDR'];
	}
	return preg_match("/[\d\.]{7,15}/", $ip, $matches) ? $matches[0] : 'unknown';
}

function hideip($ip, $type="1100")
{
	//检测IP是否为空&简单检测格式
	if(!empty($ip) and strstr($ip,"."))
	{
		$ip = explode(".",$ip);
		$type = (string)$type;
		for($i=0;$i<4;$i++)
		{
			if(!$type[$i])
			{
				$ip[$i]="*";
			}
		}
		$ip = implode(".",$ip);
		return $ip;
	}
	else
	{
		return false;
	}
}

/**
 * 返回通用$_SERVER['REQUEST_URI']
 * 只有apache支持$_SERVER['REQUEST_URI']
 *
 * @return $_SERVER['REQUEST_URI']
 */
function request_uri()
{
	if(isset($_SERVER['REQUEST_URI']))
	{
		$uri = $_SERVER['REQUEST_URI'];
	}
	else
	{
		if(isset($_SERVER['argv']))
		{
			$uri = $_SERVER['PHP_SELF'] .'?'. $_SERVER['argv'][0];
		}
		else
		{
			$uri = $_SERVER['PHP_SELF'] .'?'. $_SERVER['QUERY_STRING'];
		}
	}
	return $uri;
}

function br2nl($text)
{
   return  preg_replace('/<br\\s*?\/??>/i', '', $text);
}

function s_addslashes($string, $force = 0)
{
	!defined('MAGIC_QUOTES_GPC') && define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
	if(!MAGIC_QUOTES_GPC || $force)
	{
		if(is_array($string))
		{
			foreach($string as $key => $val)
			{
				$string[$key] = s_addslashes($val, $force);
			}
		} else {
			$string = addslashes($string);
		}
	}
	return $string;
}

function s_stripslashes($string)
{
	if(!is_array($string)) return stripslashes($string);
	foreach($string as $key => $val) $string[$key] = s_stripslashes($val);
	return $string;
}

function s_setcookie($var, $value, $life = 0, $prefix = 1)
{
	global $cookiepre, $cookiedomain, $cookiepath, $timestamp, $_SERVER;
	setcookie(($prefix ? $cookiepre : '').$var, $value, $life ? $timestamp + $life : 0, $cookiepath, $cookiedomain, $_SERVER['SERVER_PORT'] == 443 ? 1 : 0);
}

function s_htmlspecialchars($string)
{
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = s_htmlspecialchars($val);
		}
	} else {
		$string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1',
		str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string));
	}
	return $string;
}
function showmessage($msg, $url = 'javascript:history.go(-1)', $delaytime = 2)
{
	include template('showmessage');
	exit;
}

function runtime()
{
	global $start_time;
	$mtime = explode(' ', microtime());
	return number_format(($mtime[1] + $mtime[0] - $start_time), 6);
}

function cutstr($string, $length, $dot = '...', $charset = 'utf-8') {

	if(strlen($string) <= $length) {
		return $string;
	}

	$string = str_replace(array('&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'),
				array(' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);

	$strcut = '';
	if(strtolower($charset) == 'utf-8') {

		$n = $tn = $noc = 0;
		while($n < strlen($string)) {

			$t = ord($string[$n]);
			if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
				$tn = 1; $n++; $noc++;
			} elseif(194 <= $t && $t <= 223) {
				$tn = 2; $n += 2; $noc += 2;
			} elseif(224 <= $t && $t < 239) {
				$tn = 3; $n += 3; $noc += 2;
			} elseif(240 <= $t && $t <= 247) {
				$tn = 4; $n += 4; $noc += 2;
			} elseif(248 <= $t && $t <= 251) {
				$tn = 5; $n += 5; $noc += 2;
			} elseif($t == 252 || $t == 253) {
				$tn = 6; $n += 6; $noc += 2;
			} else {
				$n++;
			}

			if($noc >= $length) {
				break;
			}

		}
		if($noc > $length) {
			$n -= $tn;
		}

		$strcut = substr($string, 0, $n);

	} else {
		for($i = 0; $i < $length; $i++) {
			$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
		}
	}

	$strcut = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&#039;', '&lt;', '&gt;'), $strcut);

	return $strcut.$dot;
}

/*
 * 导入class类文件并初始化
 */
function load($file, $dir = '')
{
	$path = SITE_ROOT.($dir ? $dir.'/' : 'include/').$file;
	if(!(@include_once $path)) return false;
	if(strpos($file, '.class.php') !== false)
	{
		$classname = substr($file, 0, -10);
		return new $classname();
	}
	return true;
}

/*
 * $id 控件ID, $selectname 控件名称, $vararray 数据数组, $curtypeid 被选中的ID, $type 控件类型, $event 其它事件或限制
 *
 */
function selectradio($id, $selectname, $vararray, $curtypeid, $type='select', $event='', $event2='') 
{
	$html = '';
	
	if ($type == 'select')
	{
		$html .= '<select id="'.$id.'" name="'.$selectname.'" '.$event.">\n";
		$html .= "<option value=\"\">请选择</option>\n";
		foreach($vararray as $val) {
			$selected = $val[0] == $curtypeid ? 'selected="selected"' : '';
			$html .= "<option value=\"$val[0]\" $selected>".$val[1]."</option>\n";
		}
		$html .= '</select>';
	}
	elseif ($type == 'option')
	{
		foreach($vararray as $val)
		{
			$selected = $val[0] == $curtypeid ? 'selected="selected"' : '';
			$html .= "<option value=\"$val[0]\" $selected>".$val[1]."</option>\r\n";
		}
	}
	elseif ($type == 'radio')
	{
		foreach ($vararray as $key => $val)
		{
			$checked = ($val[0] == $curtypeid) || ($curtypeid == '' && $val[0] == 0) ? 'checked="checked"' : '';
			$html .= '<input type="radio" name="'.$selectname.'" value="'.$val[0]."\" $checked $event ";
			if($key == 0) {$html .= $event2;}
			$html .= " />$val[1] &nbsp;";
		}
	}
	elseif ($type == 'checkbox')
	{
		foreach ($vararray as $key => $val)
		{
			$checked = $val[0] == $curtypeid ? 'checked="checked"' : '';
			$html .= '<input type="checkbox" name="'.$selectname.'[]" value="'.$val[0]."\" $checked $event ";
			if($key == 0) {$html .= $event2;}
			$html .= " />$val[1] &nbsp;";
		}
	}
	return $html;
}

function censor($message) {
	require_once(SITE_ROOT.'data/cache/cache_censor.php');

	if($censor['banned']) {
		
		if(preg_match($censor['banned'], @str_replace(array(" ", "　", ",", ".", "，", "。"), '', $message))) {
			exit('banned');
		}
	}
	return empty($censor['filter']) ? $message : @preg_replace($censor['filter']['find'], $censor['filter']['replace'], $message);
}

/**
 * 时间段限制评论
 */
function periodscheck() {
	global $timestamp, $commentban;

	if($commentban) {
		$now = gmdate('G.i', $timestamp+8*3600);
		foreach(explode(",", str_replace(':', '.', $commentban)) as $period) {
			list($periodbegin, $periodend) = explode('-', $period);
			if(($periodbegin > $periodend && ($now >= $periodbegin || $now < $periodend)) || ($periodbegin < $periodend && $now >= $periodbegin && $now < $periodend)) {
				exit('commentban');
			}
		}
	}
	return TRUE;
}

/*
 *  格式化时间
 */
function s_date($timestamp, $format='Y-m-d H:i:s', $convert = 1) {
	$s = date($format, $timestamp);
	if($convert) {
		if(!isset($GLOBALS['todaytimestamp'])) {
			$GLOBALS['todaytimestamp'] = mktime(0,0,0,date(n),date(j),date(Y));
		}

		$time = $GLOBALS['timestamp'] - $timestamp;
		if($timestamp >= $GLOBALS['todaytimestamp']) {
			if($time > 3600) {
				return '<span title="'.$s.'">'.intval($time / 3600).'&nbsp;'.'小时前'.'</span>';
			} elseif($time > 1800) {
				return '<span title="'.$s.'">'.'半小时前'.'</span>';
			} elseif ($time > 900) {
				return '<span title="'.$s.'">'.'一刻钟前'.'</span>';
			} elseif($time > 60) {
				return '<span title="'.$s.'">'.intval($time / 60).'&nbsp;'.'分钟前'.'</span>';
			} elseif($time > 0) {
				return '<span title="'.$s.'">'.$time.'&nbsp;'.'秒前'.'</span>';
			} elseif($time == 0) {
				return '<span title="'.$s.'">'.'刚才'.'</span>';
			} else {
				return $s;
			}
		} elseif (($days = intval(($GLOBALS['todaytimestamp'] - $timestamp) / 86400)) >= 0 && $days < 2) {
			if($days == 0) {
				return '<span title="'.$s.'">'.'昨天'.'&nbsp;'.date('H:i:s', $timestamp).'</span>';
			} elseif($days == 1) {
				return '<span title="'.$s.'">'.'前天'.'&nbsp;'.date('H:i:s', $timestamp).'</span>';
			}
		} else {
			return $s;
		}
	} else {
		return $s;
	}
}

function sizecount($filesize)
{
	if($filesize >= 1073741824)
	{
		$filesize = round($filesize / 1073741824 * 100) / 100 . ' GB';
	}
	elseif($filesize >= 1048576)
	{
		$filesize = round($filesize / 1048576 * 100) / 100 . ' MB';
	}
	elseif($filesize >= 1024)
	{
		$filesize = round($filesize / 1024 * 100) / 100 . ' KB';
	}
	else
	{
		$filesize = $filesize . ' Bytes';
	}
	return $filesize;
}

function replacekey($content, $replacelimit = '1')
{
	require_once SITE_ROOT.'data/cache/cache_keylinks.php';
	if($keylinks)
	{
		$pattern = $replacement = array();
		foreach($keylinks as $v)
		{
			$pattern[] = '/'.preg_quote($v[0], '/').'/';
			$replacement[] = '<a href="'.$v[1].'" target="_blank" class="keylink">'.$v[0].'</a>';
		}
		$content = preg_replace($pattern, $replacement, $content, $replacelimit);
	}
	return $content;
}

if(!function_exists('image_type_to_extension'))
{
    function image_type_to_extension($type, $dot = true)
    {
        $e = array ( 1 => 'gif', 'jpeg', 'png', 'swf', 'psd', 'bmp' ,'tiff', 'tiff', 'jpc', 'jp2', 'jpf', 'jb2', 'swc', 'aiff', 'wbmp', 'xbm');
        $type = intval($type);
        if (!$type)
		{
            trigger_error( 'File Type is null...', E_USER_NOTICE );
            return null;
        }
        if(!isset($e[$type]))
		{
            trigger_error( 'Image type is wrong...', E_USER_NOTICE );
            return null;
        }
        return ($dot ? '.' : '') . $e[$type];
    }
}

function str_exists($haystack, $needle) {
	return !(strpos($haystack, $needle) === FALSE);
}

function getrobot()
{
	if(!defined('IS_ROBOT'))
	{
		$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
		$spiders = 'bot|crawl|spider|slurp|sohu-search|lycos|robozilla|google|isaac|surveybot|baiduspider|yahoo|yisou|3721|qihoo|daqi|ia_archiver|p.arthur|fast-webcrawler|java|microsoft-atl-native|turnitinbot|webgather|sleipnir|msn';
		$browsers = 'msie|netscape|opera|konqueror|mozilla';
		if(!str_exists($_SERVER['HTTP_USER_AGENT'], 'http://') && preg_match("/($browsers)/i", $useragent))
		{
			define('IS_ROBOT', FALSE);
		}
		elseif(preg_match("/($spiders)/i", $useragent))
		{
			define('IS_ROBOT', TRUE);
		}
		else
		{
			define('IS_ROBOT', FALSE);
		}
	}
	return IS_ROBOT;
}

function getids($array , $dot = ',')
{
	$ids = '';
	foreach ($array as $key => $val){
		$ids .= $val.$dot;
	}
	return substr($str , 0 , -1);
}

function implodeids($array) {
	if(!empty($array)) {
		return "'".implode("','", is_array($array) ? $array : array($array))."'";
	} else {
		return '';
	}
}

if(!function_exists('json_encode'))
{
	function json_encode($string)
	{
		$json = load('json.class.php');
		return $json->encode($string);
	}
}

if(!function_exists('json_decode'))
{
	function json_decode($string,$type = 1)
	{
		$json = load('json.class.php');
		return $json->decode($string,$type);
	}
}

function multi($num, $perpage, $curpage, $mpurl, $maxpages = 0, $page = 10, $autogoto = TRUE, $simple = FALSE)
{
	global $maxpage;
	$ajaxtarget = !empty($_GET['ajaxtarget']) ? " ajaxtarget=\"".s_htmlspecialchars($_GET['ajaxtarget'])."\" " : '';

	$shownum = $showkbd = TRUE;
	$lang['prev'] = '&lsaquo;&lsaquo;';
	$lang['next'] = '&rsaquo;&rsaquo;';

	$multipage = '';
	$mpurl .= strpos($mpurl, '?') ? '&amp;' : '?';
	$realpages = 1;
	if($num > $perpage) {
		$offset = 2;

		$realpages = @ceil($num / $perpage);
		$pages = $maxpages && $maxpages < $realpages ? $maxpages : $realpages;

		if($page > $pages) {
			$from = 1;
			$to = $pages;
		} else {
			$from = $curpage - $offset;
			$to = $from + $page - 1;
			if($from < 1) {
				$to = $curpage + 1 - $from;
				$from = 1;
				if($to - $from < $page) {
					$to = $page;
				}
			} elseif($to > $pages) {
				$from = $pages - $page + 1;
				$to = $pages;
			}
		}

		$multipage = ($curpage - $offset > 1 && $pages > $page ? '<a href="'.$mpurl.'page=1" class="first"'.$ajaxtarget.'>1 ...</a>' : '').
			($curpage > 1 && !$simple ? '<a href="'.$mpurl.'page='.($curpage - 1).'" class="prev"'.$ajaxtarget.'>'.$lang['prev'].'</a>' : '');
		for($i = $from; $i <= $to; $i++) {
			$multipage .= $i == $curpage ? '<strong>'.$i.'</strong>' :
				'<a href="'.$mpurl.'page='.$i.($ajaxtarget && $i == $pages && $autogoto ? '#' : '').'"'.$ajaxtarget.'>'.$i.'</a>';
		}

		$multipage .= ($to < $pages ? '<a href="'.$mpurl.'page='.$pages.'" class="last"'.$ajaxtarget.'>... '.$realpages.'</a>' : '').
			($curpage < $pages && !$simple ? '<a href="'.$mpurl.'page='.($curpage + 1).'" class="next"'.$ajaxtarget.'>'.$lang['next'].'</a>' : '').
			($showkbd && !$simple && $pages > $page && !$ajaxtarget ? '&nbsp;<input type="text" name="custompage" size="3" onkeydown="if(event.keyCode==13) {window.location=\''.$mpurl.'page=\'+this.value; return false;}" />' : '');

		$multipage = $multipage ? '<div class="pages">'.($shownum && !$simple ? '<em>&nbsp;'.$num.'&nbsp;</em>' : '').$multipage.'</div>' : '';
	}
	$maxpage = $realpages;
	return $multipage;
}

function multihtml($num, $perpage, $curpage, $mpurl, $maxpages = 0, $page = 10, $simple = FALSE) {
	global $maxpage;

	$shownum = TRUE;
	$lang['prev'] = '上一页';
	$lang['next'] = '下一页';
	$space = '_';
	
	$multipage = '';
	$realpages = 1;
	if($num > $perpage) {
		$offset = 2;

		$realpages = @ceil($num / $perpage);
		$pages = $maxpages && $maxpages < $realpages ? $maxpages : $realpages;
		$curpage = $curpage > $pages ? $pages : $curpage;
		
		if($page > $pages) {
			$from = 1;
			$to = $pages;
		} else {
			$from = $curpage - $offset;
			$to = $from + $page - 1;
			if($from < 1) {
				$to = $curpage + 1 - $from;
				$from = 1;
				if($to - $from < $page) {
					$to = $page;
				}
			} elseif($to > $pages) {
				$from = $pages - $page + 1;
				$to = $pages;
			}
		}

		$multipage = ($curpage - $offset > 1 && $pages > $page ? '<a href="'.$mpurl.'.shtml" class="first">1 ..</a>' : '').
			($curpage > 1 && !$simple ? ($curpage == 2 ? '<a href="'.$mpurl.'.shtml" class="prev">'.$lang['prev'].'</a>' : '<a href="'.$mpurl.$space.($curpage - 1).'.shtml" class="prev">'.$lang['prev'].'</a>') : '');
		for($i = $from; $i <= $to; $i++) {
			$multipage .= $i == $curpage ? '<strong>'.$i.'</strong>' :
				($i == 1 ? '<a href="'.$mpurl.'.shtml">'.$i.'</a>' : '<a href="'.$mpurl.$space.$i.'.shtml">'.$i.'</a>');
		}

		$multipage .= ($to < $pages ? '<a href="'.$mpurl.$space.$pages.'.shtml" class="last">.. '.$realpages.'</a>' : '').
			($curpage < $pages && !$simple ? '<a href="'.$mpurl.$space.($curpage + 1).'.shtml" class="next">'.$lang['next'].'</a>' : '');

		$multipage = $multipage ? '<div class="pages">'.($shownum && !$simple ? '<em>&nbsp;'.$num.'&nbsp;</em>' : '').$multipage.'</div>' : '';
	}
	$maxpage = $realpages;
	return $multipage;
}

/*
 * 过滤HTML字符
 */
function HConvert($var)
{
	if (is_array($var))
	{
		foreach ($var as $key => $value)
		{
			$var[$key] = HConvert($value);
		}
	}
	else
	{
		$var = str_replace(array('"', '\'', '<', '>', "\t", "\r"), array('&quot;', '&#39;', '&lt;', '&gt;', '&nbsp;&nbsp;', ''), $var);
	}
	return $var;
}


/*
 * HTML危险代码过滤
 * @param string $string 过滤字符
 */
function SafeConvert($string)
{
	$pattern = array('/(javascript|jscript|js|vbscript|vbs|about):/i','/on(mouse|exit|error|click|dblclick|key|load|unload|change|move|submit|reset|cut|copy|select|start|stop)/i','/<script([^>]*)>/i','/<iframe([^>]*)>/i','/<frame([^>]*)>/i','/<link([^>]*)>/i','/@import/i');
	$replace = array('','','&lt;script${1}&gt;','&lt;iframe${1}&gt;','&lt;frame${1}&gt;','&lt;link${1}&gt;','');
	$string = preg_replace($pattern, $replace, $string);
	$string = str_replace(array('</script>', '</iframe>', '&#'), array('&lt;/script&gt;', '&lt;/iframe&gt;', '&amp;#'), $string);
	return $string;
}

/**
 * 转换tag标签为链接形式
 *
 * @param string $keywords
 * @return string
 */
function tag($keywords)
{
	$tag = explode(',', str_replace('，', ',', $keywords));
	foreach ($tag as $val)
	{
		$tagstr .= "<a href=\"/tag/".rawurlencode($val).".html\" target=\"_blank\">".$val."</a>,";
	}
	$tagstr = substr($tagstr, 0, -1);
	return $tagstr;
}

function mkpath($savepath, $mode = 0777)
{
	$allpath = explode('/', $savepath);
	$path = '';
	for($i=0; $i<count($allpath); $i++)
	{
		$path .= $allpath[$i].'/';
		if(empty($allpath[$i])) continue;
		if(file_exists($path))
		{
			continue;
		} else {
			@mkdir($path, $mode);
			@touch($path.'/index.htm');
		}
	}
}

function createhtml($file)
{
	$data = ob_get_contents();
	ob_clean();
	mkpath(dirname($file));
	$strlen = file_put_contents($file, $data);
	@chmod($file, 0777);
	return $strlen;
}

function ssi($file)
{
	if(!file_exists(SITE_ROOT.$file)) return false;
	return ($shtml && defined('CREATEHTML')) ? '<!--#include virtual="'.FILE_PATH.$file.'"-->' : @file_get_contents(SITE_ROOT.$file);
}

function block($pageid, $blockno)
{
	echo ssi('data/block/'.$pageid.'_'.$blockno.'.html');
}

function string2array($data)
{
	if($data == '') return array();
	eval("\$array = $data;");
	return $array;
}

function array2string($data, $isformdata = 1)
{
	if($data == '') return '';
	if($isformdata) $data = s_stripslashes($data);
	return addslashes(var_export($data, TRUE));
}

function output()
{
	return $runtime = runtime();
}

function writelog($file, $log)
{
	$yearmonth = date('Ym', time());
	$logdir = SITE_ROOT.'data/log/';
	$logfile = $logdir.$yearmonth.'_'.$file.'.php';

	if($fp = @fopen($logfile, 'a')) {
		@flock($fp, 2);
		$log = is_array($log) ? $log : array($log);
		foreach($log as $v) {
			fwrite($fp, "<?PHP exit;?>\t".str_replace(array('<?', '?>'), '', $v)."\n");
		}
		fclose($fp);
	}
}

function checktplrefresh($maintpl, $subtpl, $comparetime, $templateid, $tpldir)
{
	global $tplrefresh;

	if(empty($comparetime) || $tplrefresh == 1 || ($tplrefresh > 1 && !($GLOBALS['timestamp'] % $tplrefresh))) {
		if(empty($comparetime) || @filemtime($subtpl) > $comparetime) {
			require_once SITE_ROOT.'include/template.func.php';
			template_compile($maintpl, $templateid, $tpldir);
			return TRUE;
		}
	}
	return 	FALSE;
}

function template($file, $templateid = 0, $tpldir = '')
{
	global $inajax;
	
	$templateid = $templateid ? $templateid : TEMPLATEID;
	$tpldir = $tpldir ? $tpldir : TPLDIR;
	
	$file .= $inajax && ($file == 'header' || $file == 'footer') ? '_ajax' : '';

	$tplfile = SITE_ROOT.'templates/'.$tpldir.'/'.$file.'.htm';
	$objfile = SITE_ROOT.'data/templates/'.$templateid.'_'.$file.'.tpl.php';
	if(!file_exists($tplfile)) {
		$tplfile = SITE_ROOT.'templates/default/'.$file.'.htm';
	}
	@checktplrefresh($tplfile, $tplfile, filemtime($objfile), $templateid, $tpldir);

	return $objfile;
}

function admin_tpl($file = 'login')
{
	return SITE_ROOT.'admin/templates/'.$file.'.tpl.php';
}
?>